/*
四个画面
原图 北京消除  开操作 闭操作
*/

#include <iostream>
#include <sstream>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/video.hpp>
#include "func.h"
using namespace cv;
using namespace std;
const char* params
    = "{ help h         |           | Print usage }"
      "{ input          | test.avi  | Path to a video or a sequence of image }"
      "{ lr             | -1        | learning rate of MOG2 }"
      "{ algo           | MOG2      | Background subtraction method (KNN, MOG2) }";
int main(int argc, char* argv[])
{
    CommandLineParser parser(argc, argv, params);
    parser.about( "This program shows how to use background subtraction methods provided by "
                  " OpenCV. You can process both videos and images.\n" );
    if (parser.has("help"))
    {
        //print help information
        parser.printMessage();
    }
    //create Background Subtractor objects
    vector<string> files;
    getFileNames( parser.get<String>("input")  , files);
    for (int i = 0; i < files.size(); ++i){
    	string filePath = parser.get<String>("input") +"/"+ files[i];
	    cout<<files[i]<<endl;
	    Ptr<BackgroundSubtractor> pBackSub;
    	if (parser.get<String>("algo") == "MOG2")
        	pBackSub = createBackgroundSubtractorMOG2();
    	else
        	pBackSub = createBackgroundSubtractorKNN();
	    VideoCapture capture(filePath);
        if (!capture.isOpened()){
            //error in opening the video input
            cerr << "Unable to open: " << parser.get<String>("input") << endl;
            return 0;
        }
        Mat frame, fgMask;
        VideoWriter videoWriter;
	    int width =(int)capture.get(CAP_PROP_FRAME_WIDTH);
	    int height = (int)capture.get(CAP_PROP_FRAME_HEIGHT);
        Size S = Size(2*(int)capture.get(CAP_PROP_FRAME_WIDTH),2*(int)capture.get(CAP_PROP_FRAME_HEIGHT));
        int fps = capture.get(CAP_PROP_FPS);
        videoWriter.open("output/OUT_"+files[i]+".avi", cv::VideoWriter::fourcc('M','J','P','G'),fps ,S);
        while (true) {
            capture >> frame;
            if (frame.empty())
                break;
            //update the background model
       	    if (parser.get<String>("algo") == "MOG2")
                pBackSub->apply(frame, fgMask,parser.get<double>("lr"));
            else
                pBackSub->apply(frame, fgMask);
            //get the frame number and write it on the current frame
            rectangle(frame, cv::Point(10, 2), cv::Point(100,20),
                      cv::Scalar(255,255,255), -1);
            stringstream ss;
            ss << capture.get(CAP_PROP_POS_FRAMES);
            string frameNumberString = ss.str();
            putText(frame, frameNumberString.c_str(), cv::Point(15, 15),
                    FONT_HERSHEY_SIMPLEX, 0.5 , cv::Scalar(0,0,0));
            //show the current frame and the fg masks
	        Mat resultImg = Mat(2*height, 2*width, CV_8UC3, Scalar::all(0));
  	        Mat ROI_1 = resultImg(Rect(0, 0, width, height));
      	    Mat ROI_2 = resultImg(Rect(width, 0, width, height)); 
      	    Mat ROI_3 = resultImg(Rect(0, height, width, height));
      	    Mat ROI_4 = resultImg(Rect(width, height, width, height));
            //imshow("Frame", frame);
            //imshow("FG Mask", fgMask);
  	        frame.copyTo(ROI_1);
            Mat fgMask3Channels = convertTo3Channels(fgMask);
  	        fgMask3Channels.copyTo(ROI_2);	
           //kai 
			Mat se = getStructuringElement(0,Size(2,2) ); //构造矩形结构元素
            erode(fgMask, fgMask, se, Point(-1, -1), 2); //执行腐蚀操作
            dilate(fgMask, fgMask, se, Point(-1, -1), 2); //执行膨胀操作
            fgMask3Channels = convertTo3Channels(fgMask);
  	        fgMask3Channels.copyTo(ROI_3);	
            //bi
			se = getStructuringElement(0,Size(3,3) ); //构造矩形结构元素
            dilate(fgMask, fgMask, se, Point(-1, -1), 2); //执行膨胀操作
            erode(fgMask, fgMask, se, Point(-1, -1), 2); //执行腐蚀操作
            fgMask3Channels = convertTo3Channels(fgMask);
  	        fgMask3Channels.copyTo(ROI_4);	
            
			videoWriter.write(resultImg);
            //get the input from the keyboard
            int keyboard = waitKey(1);
            if (keyboard == 'q' || keyboard == 27)
                break;
        }
        videoWriter.release();
    }
        return 0;
}
